import warnings
from urllib import parse
from DrissionPage._units.listener import DataPacket
from DrissionPage import WebPage
from DataRecorder import Recorder


class VideoParser(object):
    def __init__(self, page):
        self.page: WebPage = page
        self.modal_id = None
        self.author = None
        self.title = None
        self.recorder = Recorder(r'data/video.xlsx')

    def get_video_info(self):
        warnings.warn('该函数已过时，请使用get_video_detail()函数', DeprecationWarning)
        # 获取视频作者
        author: str = self.page.ele("tag:div@@class=account-name@@data-e2e=feed-video-nickname").text
        self.author = author.removeprefix('@')
        print(f'视频作者为：{self.author}')
        # 获取视频标题
        self.title = self.page.ele("tag:div@data-e2e=video-desc").text
        print(f'视频标题为：{self.title}')
        self.get_video_url()

    def get_video_detail(self):
        """获取视频id"""
        tab = self.page.new_tab(f'https://www.douyin.com/video/{self.modal_id}')
        tab.listen.start(['/aweme/v1/web/aweme/detail/'])
        tab.wait(2)
        data_packet: DataPacket = tab.listen.wait(timeout=3)
        if data_packet:
            self.parse_video(data_packet)
        tab.close()

    def get_video_url(self):
        """获取视频id"""
        parse_url = parse.urlparse(self.page.url)
        self.modal_id = parse.parse_qs(parse_url.query).get('modal_id', [''])[0]  # 获取视频id（modal_id）
        return self.modal_id

    def parse_video(self, data_packet: DataPacket):
        # 获取视频作者数据包
        aweme_data = data_packet.response.body
        aweme_detail = aweme_data.get('aweme_detail', {})
        author_info = aweme_detail.get('author', {})
        author_id = author_info.get('uid', '')
        author_user_id = aweme_detail.get('author_user_id', '')
        author_nickname = author_info.get('nickname', '')
        author_signature = author_info.get('signature', '')
        author_age = author_info.get('user_age', '')

        aweme_id = aweme_detail.get('aweme_id', '')
        aweme_desc = aweme_detail.get('desc', '')
        aweme_create_time = aweme_detail.get('create_time', '')
        aweme_is_ads = aweme_detail.get('is_ads', '')

        music = aweme_detail.get('music', {})
        music_title = music.get('title', '')
        music_url = music.get('play_url', {}).get('uri', '')

        video = aweme_detail.get('video', {})
        video_url = ";".join(video.get('play_addr', {}).get('url_list', ['']))
        video_tags = ";".join([tag.get('tag_name', '') for tag in video.get('tags', [])])

        self.author = author_nickname
        self.title = aweme_desc

        self.recorder.add_data({
            '视频ID': aweme_id,
            '作者': author_nickname,
            '作者ID': author_id,
            '作者用户ID': author_user_id,
            '个性签名': author_signature,
            '作者年龄': author_age,
            '视频描述': aweme_desc,
            '创建时间': aweme_create_time,
            '是否广告': aweme_is_ads,
            '背景音乐': music_title,
            '音乐地址': music_url,
            '视频地址': video_url,
            '视频标签': video_tags,
        })
        self.recorder.record()
